﻿Imports AjaxControlToolkit
Imports System.IO


Public Class AdvertiseNew
    Inherits System.Web.UI.Page

    Public numAcc As Integer
    Public Shared totalCost As Integer
    Public dbManager As DBManager = New DBManager()
    Public Shared selectedOutlet As Integer = -2

    'To set masterpage 
    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit

        'Check if user is null
        If (Session("user") IsNot Nothing) Then
            'Retrieve userAcc details from session
            Dim userLoggedIn As userAcc = Session("user")
            'Check if user is admin, assign masterpage respectively
            If userLoggedIn.isAdmin Then
                Me.MasterPageFile = "~/MasterPage/Admin.Master"
            Else
                Me.MasterPageFile = "~/MasterPage/User.Master"
            End If
        Else

            'For anonymous users
            Me.MasterPageFile = "~/MasterPage/User.Master"
            'Enable this line to prevent anonymous users from entering this page
            ' Response.Redirect("~/Login.aspx")
        End If

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'Initialize listview
        If (Not IsPostBack) Then

            If (Request.QueryString("type") = "banner") Then
                hidLastTab.Value = 1
            End If
            Dim objComments As SqlDataSource = SqlDataSourceSelectedItems
            Dim parameter As Parameter = objComments.SelectParameters(0)

            If (Session("user") IsNot Nothing) Then
                Dim userLoggedIn As userAcc = Session("user")
                parameter.DefaultValue = userLoggedIn.userID
                btnNextSEO.Enabled = False
                btnNextSEO.ToolTip = "No selected branches"

            Else
                parameter.DefaultValue = 0
                btnNextSEO.ToolTip = "Please login first"
                btnNextSEO.Enabled = False
            End If
            lvSelectedItems.DataSourceID = objComments.ID
            lvSelectedItems.DataBind()
            numAcc = 1

            rvBanner.MinimumValue = System.DateTime.Now.AddDays(7).Date
            rvBanner.MaximumValue = System.DateTime.Now.AddDays(7).AddYears(1).Date
            selectedOutlet = False
        End If
        btnNextSEO.Enabled = False
        btnSubmitBannerComplete.Enabled = False
        If (Session("user") IsNot Nothing) Then
            If (FileUpload1.Enabled = False) Then
                FileUpload1.Enabled = True
                FileUpload1.ToolTip = ""
            End If

            btnImageUpload.Enabled = True
            btnImageUpload.ToolTip = ""
            If (FileUpload1.HasFile And tbxBannerDate.Text.Count > 0 And selectedOutlet > -1) Then
                btnSubmitBanner.Enabled = True
            End If
            Dim userLoggedIn As userAcc = Session("user")
            Dim objDataSource As SqlDataSource = SqlDataSourceSelectedBanner
            Dim parameter As Parameter = objDataSource.SelectParameters(0)
            parameter.DefaultValue = userLoggedIn.userID
            lvSelectedBanner.DataSourceID = objDataSource.ID
        Else
            FileUpload1.Enabled = False
            FileUpload1.ToolTip = "Please login first"
            btnImageUpload.Enabled = False
            btnImageUpload.ToolTip = "Please login first"
        End If

    End Sub

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSearch.Click

        lvSelectedItems.DataBind()
        lvSearchResults.DataBind()
    End Sub

    Protected Sub lvSelectedItems_ItemBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvSelectedItems.ItemDataBound
        'If listview has items, enable the next button
        btnNextSEO.Enabled = True
        btnNextSEO.ToolTip = ""
    End Sub

    'As each item in lvSearchResults are being bounded
    Protected Sub lvSearchResults_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvSearchResults.ItemDataBound
        Dim lblPriority As Label = e.Item.FindControl("priorityLabel")
        Dim lblPrioritized As Label = e.Item.FindControl("lblPrioritized")
        Dim lblAvailable As Label = e.Item.FindControl("lblAvailable")
        Dim lbName As LinkButton = e.Item.FindControl("lbName")
        Dim lblName As Label = e.Item.FindControl("lblName")
        Try
            'Visibility for priority text and whether name is link or not.
            If Convert.ToInt32(lblPriority.Text) > 0 Then
                lblPrioritized.Visible = True
                lblAvailable.Visible = False
                lbName.Visible = False
                lblName.Visible = True
            Else
                lblPrioritized.Visible = False
                lblAvailable.Visible = True
                lblName.Visible = False
                lbName.Visible = True
            End If
        Catch ex As Exception
        End Try

        'Hide this row if it has been added already
        If (Session("user") IsNot Nothing) Then
            Dim lblOutletID As Label = e.Item.FindControl("lblOutletID")
            Dim userLoggedIn As userAcc = Session("user")
            If dbManager.checkTempItemExists(userLoggedIn.userID, Convert.ToInt32(lblOutletID.Text)) Or dbManager.checkAdvItemExists(userLoggedIn.userID, Convert.ToInt32(lblOutletID.Text)) Then
                e.Item.Visible = False
            End If
        End If

    End Sub

    'Item command for lvSearchResults
    Protected Sub lvSearchResults_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles lvSearchResults.ItemCommand
        If e.CommandName = "select" Then
            Dim lblOutletID As Label = e.Item.FindControl("lblOutletID")
            Dim lbName As LinkButton = e.Item.FindControl("lbName")
            If (Session("user") IsNot Nothing) Then
                Dim userLoggedIn As userAcc = Session("user")
                dbManager.addTempItem(userLoggedIn.userID, lbName.Text, Convert.ToInt32(lblOutletID.Text))
                lvSelectedItems.DataBind()
            Else
                MsgBox("Please login first", MsgBoxStyle.OkOnly)
            End If

        End If

    End Sub

    'Delete a selected item from the list
    Protected Sub lvSelectedItems_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles lvSelectedItems.ItemCommand
        If e.CommandName = "deleteTempItem" Then
            Dim lblTempID As Label = e.Item.FindControl("temp_adv_IDLabel")
            dbManager.deleteTempItem(Convert.ToInt32(lblTempID.Text))
            lvSelectedItems.DataBind()
            lvSearchResults.DataBind()
        End If
    End Sub

    Protected Sub btnNextSEO_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnNextSEO.Click
        pnlSEOSelectDuration.Visible = True
        pnlSEOSelectOutlets.Visible = False

        'initializePanel(1)
        'initializePanel(2)
        'initializePanel(3)
        Dim objSelectedItem As SqlDataSource = SqlDataSourceSelectedItemsDuration
        Dim parameter As Parameter = objSelectedItem.SelectParameters(0)
        Dim userLoggedIn As userAcc = Session("user")
        parameter.DefaultValue = userLoggedIn.userID
        lvDuration.DataSourceID = SqlDataSourceSelectedItemsDuration.ID
        lvDuration.DataBind()
    End Sub

    Protected Sub accDurationCreateControls(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim accordionPane As AccordionPane = sender.FindControl("accDurationPane")

        'Dynamically create textbox
        Dim tbxDatePicker As TextBox = New TextBox()
        tbxDatePicker.ID = "tbxDatePicker" + numAcc.ToString()
        tbxDatePicker.CausesValidation = True
        tbxDatePicker.AutoPostBack = True
        tbxDatePicker.Width = New Unit(90, UnitType.Pixel)
        AddHandler (tbxDatePicker.TextChanged), AddressOf datepicker_datePicked
        accordionPane.ContentContainer.FindControl("placeHolderTextBox").Controls.Add(tbxDatePicker)

        'Dynamically create range validator
        Dim rvDatePicker As RangeValidator = New RangeValidator
        rvDatePicker.MinimumValue = System.DateTime.Now.AddDays(7).Date
        rvDatePicker.MaximumValue = System.DateTime.Now.AddDays(7).AddYears(1).Date
        rvDatePicker.ErrorMessage = "Must be at least 7 days in advance and within a year"
        rvDatePicker.Type = ValidationDataType.Date
        rvDatePicker.ID = "rvDatePicker" + numAcc.ToString()
        rvDatePicker.Display = ValidatorDisplay.Dynamic
        rvDatePicker.ControlToValidate = tbxDatePicker.ID
        'rvDatePicker.ForeColor = Drawing.Color.FromArgb(251, 238, 213)
        rvDatePicker.Display = ValidatorDisplay.None
        accordionPane.ContentContainer.FindControl("placeHolderTextBox").Controls.Add(rvDatePicker)

        'Dynamically create calenderExtender
        Dim calExDate As CalendarExtender = New CalendarExtender()
        calExDate.TargetControlID = tbxDatePicker.ID
        calExDate.Enabled = True
        calExDate.Format = "dd/MM/yyyy"
        calExDate.ID = "calExDate" + numAcc.ToString()
        accordionPane.ContentContainer.FindControl("placeHolderTextBox").Controls.Add(calExDate)

        'Dynamically create 
        Dim valCallEx As ValidatorCalloutExtender = New ValidatorCalloutExtender()
        valCallEx.PopupPosition = ValidatorCalloutPosition.Right
        valCallEx.TargetControlID = rvDatePicker.ID
        valCallEx.ID = "valCallEx" + numAcc.ToString()
        accordionPane.ContentContainer.FindControl("placeHolderTextBox").Controls.Add(valCallEx)

        numAcc = numAcc + 1
    End Sub

    Protected Sub lvDuration_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvDuration.ItemDataBound

        Dim lblTempID As Label = e.Item.FindControl("temp_adv_IDLabel")
        'Initialize the accordion to fill it with info
        Dim accordion As Accordion = e.Item.FindControl("accDuration")
        Dim accordionPane As AccordionPane = accordion.Panes(0)
        Dim lblName As Label = accordionPane.FindControl("nameLabel")
        Dim lblNameAcc As Label = e.Item.FindControl("lblName")
        'Set the name of the outlet
        lblName.Text = lblNameAcc.Text

    End Sub

    Protected Sub accDuration_ItemCommand(ByVal sender As Object, ByVal e As AccordionCommandEventArgs)
        Dim accordionParent As Accordion = e.Container.Parent.Parent
        Dim divHeader As System.Web.UI.HtmlControls.HtmlGenericControl = accordionParent.FindControl("divHeader")
        Dim btnConfirm As Button = accordionParent.FindControl("btnAccConfirm")
        Dim lvDuration As ListViewDataItem = e.Container.Parent.Parent.Parent
        Dim imgNotDone As Image = lvDuration.FindControl("imgNotDone")
        Dim imgDone As Image = lvDuration.FindControl("imgDone")
        Dim lblSubCost As Label = lvDuration.FindControl("lblSubCost")
        Dim ddlAccDuration As DropDownList = e.Container.Parent.FindControl("ddlAccDuration")
        Dim tbxDatePicker As TextBox = e.Container.Parent.FindControl("placeHolderTextBox").Controls(0)
        If e.CommandName = "Confirm" Then

            divHeader.Attributes("class") = "alert alert-success"
            accordionParent.SelectedIndex = -1
            btnConfirm.Text = "Update"
            btnConfirm.CommandName = "Update"
            imgNotDone.Visible = False
            imgDone.Visible = True

            tbxDatePicker.Enabled = False
            Select Case (ddlAccDuration.SelectedValue)
                Case 1
                    lblSubCost.Text = "400"
                Case 2
                    lblSubCost.Text = "1000"
                Case 3
                    lblSubCost.Text = "1800"
                Case 4
                    lblSubCost.Text = "3300"
            End Select
            lblSubCost.Visible = True
            lblTotalCostSEO.Text = (Convert.ToInt32(lblTotalCostSEO.Text) + Convert.ToInt32(lblSubCost.Text)).ToString()
            ddlAccDuration.Enabled = False

            'To check whether to disable or enable the next button
            btnSEONext.Enabled = True
            Dim lvDurParent As ListView = lvDuration.BindingContainer
            For Each item As ListViewItem In lvDurParent.Items
                Dim divHead As HtmlGenericControl = item.FindControl("accDuration").FindControl("accDurationPane").FindControl("divHeader")
                If Not divHead.Attributes("class") = "alert alert-success" Then
                    btnSEONext.Enabled = False
                End If
            Next


        ElseIf e.CommandName = "Update" Then
            lblTotalCostSEO.Text = (Convert.ToInt32(lblTotalCostSEO.Text) - Convert.ToInt32(lblSubCost.Text)).ToString()

            divHeader.Attributes("class") = "alert alert-error"
            btnConfirm.Text = "Confirm"
            btnConfirm.CommandName = "Confirm"
            imgNotDone.Visible = True
            imgDone.Visible = False
            tbxDatePicker.Enabled = True
            lblSubCost.Visible = False
            ddlAccDuration.Enabled = True

            'To check whether to disable or enable the next button
            btnSEONext.Enabled = True
            Dim lvDurParent As ListView = lvDuration.BindingContainer
            For Each item As ListViewItem In lvDurParent.Items
                Dim divHead As HtmlGenericControl = item.FindControl("accDuration").FindControl("accDurationPane").FindControl("divHeader")
                If Not divHead.Attributes("class") = "alert alert-success" Then
                    btnSEONext.Enabled = False
                End If
            Next

        End If

    End Sub

    Protected Sub ddlAccDuration_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
    End Sub

    'On selected date change for SEO
    Protected Sub datepicker_datePicked(ByVal sender As Object, ByVal e As EventArgs)
        Dim tbxDatePicker As TextBox = sender
        Dim lblAccEndDate As Label = tbxDatePicker.Parent.FindControl("lblAccEndDate")
        Dim startDate = DateTime.Parse(tbxDatePicker.Text)
        Dim endDate As DateTime = DateTime.Now
        Dim ddlAccDuration As DropDownList = tbxDatePicker.Parent.FindControl("ddlAccDuration")
        Dim selectedDuration = ddlAccDuration.SelectedValue

        If tbxDatePicker.Text.Trim.Length > 0 Then
            Select Case (selectedDuration)
                Case 1
                    endDate = startDate.AddMonths(1)

                Case 2
                    endDate = startDate.AddMonths(3)
                Case 3
                    endDate = startDate.AddMonths(6)
                Case 4
                    endDate = startDate.AddYears(1)
            End Select
            lblAccEndDate.Text = endDate.ToShortDateString()
            Dim btnConfirm As Button = tbxDatePicker.Parent.FindControl("btnAccConfirm")
            btnConfirm.Enabled = True
        End If

    End Sub

    'Return to SEO step 1
    Protected Sub btnSEOBack_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSEOBack.Click
        pnlSEOSelectDuration.Visible = False
        pnlSEOSelectOutlets.Visible = True

    End Sub

    'To advertise dashboard page
    Protected Sub btnSEONext_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSEONext.Click
        'Clear database to prevent duplicates first
        Dim userLoggedIn As userAcc = Session("user")
        dbManager.clearSEO(userLoggedIn.userID)

        Dim lvDurParent As ListView = lvDuration
        For Each item As ListViewItem In lvDurParent.Items
            Dim accPane As AccordionPane = item.FindControl("accDuration").FindControl("accDurationPane")
            Dim ddlAccDuration As DropDownList = accPane.FindControl("ddlAccDuration")
            Dim lblName As Label = item.FindControl("lblName")
            Dim tbxDatePicker As TextBox = accPane.FindControl("placeHolderTextBox").Controls(0)
            Dim lblAccEndDate As Label = accPane.FindControl("lblAccEndDate")
            Dim temp_adv_IDLabel As Label = item.FindControl("temp_adv_IDLabel")
            Dim lblOutletID As Label = item.FindControl("lblOutletID")

            Dim duration = ddlAccDuration.SelectedItem.Text
            Dim name = lblName.Text
            Dim startDate = tbxDatePicker.Text
            Dim endDate = lblAccEndDate.Text
            Dim outletID = lblOutletID.Text



            dbManager.addSEOItem(userLoggedIn.userID, name, outletID, startDate, endDate, duration)

        Next
        dbManager.clearSEOTemp(userLoggedIn.userID)
        pnlSEOSelectDuration.Visible = False
        pnlSEOSelectOutlets.Visible = False
        Response.Redirect("AdvertiseDashboard.aspx")
    End Sub

    'On selected date change for banner
    Protected Sub tbxBannerDate_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles tbxBannerDate.TextChanged
        'depending on the dropdownlist
        Dim selectedDate As Date = DateTime.Parse(tbxBannerDate.Text)
        Dim endDate As Date
        Select Case (ddlBannerDuration.SelectedIndex)
            Case 0
                endDate = selectedDate.AddMonths(1)
                lblCost.Text = "400"
            Case 1
                endDate = selectedDate.AddMonths(3)
                lblCost.Text = "1000"
            Case 2
                endDate = selectedDate.AddMonths(6)
                lblCost.Text = "1800"
            Case 3
                endDate = selectedDate.AddYears(1)
                lblCost.Text = "3300"

        End Select
        lblEndDateData.Text = endDate.ToShortDateString()

        If FileUpload1.HasFile And selectedOutlet > -1 Then
            btnSubmitBanner.Enabled = True
        End If
    End Sub

    'Dropdownlist banner duration selectedIndexChange event
    Protected Sub ddlBannerDuration_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlBannerDuration.SelectedIndexChanged

        If (tbxBannerDate.Text.Count > 0) Then
            Try
                'depending on the dropdownlist
                Dim selectedDate As Date = DateTime.Parse(tbxBannerDate.Text)
                Dim endDate As Date
                Select Case (ddlBannerDuration.SelectedIndex)
                    Case 0
                        endDate = selectedDate.AddMonths(1)
                        lblCost.Text = "400"
                    Case 1
                        endDate = selectedDate.AddMonths(3)
                        lblCost.Text = "1000"
                    Case 2
                        endDate = selectedDate.AddMonths(6)
                        lblCost.Text = "1800"
                    Case 3
                        endDate = selectedDate.AddYears(1)
                        lblCost.Text = "3300"

                End Select
                lblEndDateData.Text = endDate.ToShortDateString()

            Catch ex As Exception

            End Try

        End If

    End Sub

    'Upload image temporarily
    Protected Sub btnImageUpload_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnImageUpload.Click

        If (FileUpload1.HasFile) Then
            imgPreview.Visible = True
            Dim imgLength As Integer = FileUpload1.PostedFile.ContentLength
            Dim img As HttpPostedFile = FileUpload1.PostedFile
            Dim imgName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
            Dim userLoggedIn As userAcc = Session("user")
            Dim tempImageID As Integer = dbManager.addImageBanner(imgName, img, imgLength, userLoggedIn.userID)
            If selectedOutlet > -1 Then
                btnSubmitBanner.Enabled = True
                btnSubmitBanner.ToolTip = ""
            End If

            imgPreview.ImageUrl = "BannerHttpHandler.ashx?id=" + tempImageID.ToString()
            hfImageTemp.Value = tempImageID
        End If

    End Sub

    Protected Sub btnSubmitBanner_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmitBanner.Click
        If Not hfImageTemp.Value = 0 Then

            dbManager.updateImageBanner(hfImageTemp.Value, Date.Parse(tbxBannerDate.Text), Date.Parse(lblEndDateData.Text), Convert.ToInt32(lblCost.Text), selectedOutlet)
            Dim userLoggedIn As userAcc = Session("user")
            dbManager.deleteInitialImageBanner(userLoggedIn.userID)

            btnSubmitBanner.Enabled = False
            ddlBannerDuration.SelectedIndex = 0
            tbxBannerDate.Text = ""
            lblEndDateData.Text = ""
            imgPreview.Visible = False
            lvSelectedBanner.DataBind()
        End If
    End Sub

    Protected Sub lvSelectedBanner_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvSelectedBanner.ItemDataBound
        Dim image_nameLabel As Label = e.Item.FindControl("image_nameLabel")
        Dim costLabel As Label = e.Item.FindControl("costLabel")
        Dim imageName As String = image_nameLabel.Text
        If (imageName.Length > 30) Then
            image_nameLabel.Text = imageName.Substring(0, 30) + "..."

        End If
        totalCost = totalCost + Convert.ToInt32(costLabel.Text)
        lblTotalCost.Text = totalCost
        btnSubmitBannerComplete.Enabled = True
    End Sub

    Protected Sub lvSelectedBanner_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles lvSelectedBanner.ItemCommand
        Dim adv_image_IDLabel As Label = e.Item.FindControl("adv_image_IDLabel")
        Select Case e.CommandName
            Case "preview"
                imgPreview.Visible = True
                imgPreview.ImageUrl = "BannerHttpHandler.ashx?id=" + adv_image_IDLabel.Text
            Case "remove"
                imgPreview.ImageUrl = ""
                imgPreview.Visible = False
                dbManager.deleteImageBanner(Convert.ToInt32(adv_image_IDLabel.Text))
                lvSelectedBanner.DataBind()


        End Select
    End Sub

    Protected Sub btnSubmitBannerComplete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmitBannerComplete.Click
        For Each item As ListViewItem In lvSelectedBanner.Items
            Dim adv_image_IDLabel As Label = item.FindControl("adv_image_IDLabel")
            dbManager.updateImageBannerUnconfirmed(Convert.ToInt32(adv_image_IDLabel.Text))

        Next
        Response.Redirect("AdvertiseDashboard.aspx")
    End Sub

    Protected Sub tbxSearchBannerOutlet_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles tbxSearchBannerOutlet.TextChanged
        lvSearchBanner.DataBind()
    End Sub

    Protected Sub lvSearchBanner_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles lvSearchBanner.ItemCommand
        If e.CommandName = "selectOutlet" Then
            Dim lblOutlet As Label = e.Item.FindControl("outlet_IDLabel")
            selectedOutlet = Convert.ToInt32(lblOutlet.Text)

            For Each item As ListViewItem In lvSearchBanner.Items
                Dim outletItem As Label = item.FindControl("outlet_IDLabel")
                Dim lbName As LinkButton = item.FindControl("nameLabel")
                If outletItem.Text = selectedOutlet.ToString() Then

                    lbName.CssClass = "label label-info"
                Else
                    lbName.CssClass = ""
                End If
            Next

        End If
    End Sub

    Protected Sub lvSearchBanner_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lvSearchBanner.ItemDataBound
        Dim lbName As LinkButton = e.Item.FindControl("nameLabel")
        Dim lblOutlet As Label = e.Item.FindControl("outlet_IDLabel")
        If lblOutlet.Text = selectedOutlet.ToString() Then
            lbName.CssClass = "label label-info"
        Else
            lbName.CssClass = ""
        End If

    End Sub
End Class